<template>
  <!-- 定义 tab 组件：撰写/回复等 -->
  <DefineTab v-slot="{ active, text, itemClick }">
    <span
      class="inline-block w-1/2 rounded-full cursor-pointer text-center leading-[30px] relative z-1 text-[5C6370] hover:text-black"
      :class="active ? 'text-black shadow-md' : 'hover:bg-[#DDDFE3]'"
      @click="itemClick"
    >
      {{ text }}
    </span>
  </DefineTab>
  <!-- 定义 label 组件：长度/格式/语气/语言等 -->
  <DefineLabel v-slot="{ label, hint, hintClick }">
    <h3 class="mt-5 mb-3 flex items-center justify-between text-[14px]">
      <span>{{ label }}</span>
      <span
        @click="hintClick"
        v-if="hint"
        class="flex items-center text-[12px] text-[#846af7] cursor-pointer select-none"
      >
        <Icon icon="ep:question-filled" />
        {{ hint }}
      </span>
    </h3>
  </DefineLabel>

  <div class="flex flex-col" v-bind="$attrs">
    <!-- tab -->
    <div class="w-full pt-2 bg-[#f5f7f9] flex justify-center">
      <!-- <ReuseLabel label="日报生成器"  /> -->
      <ReuseLabel  :label="formData.name"/>
      <!-- <el-tag>{{ formData.name }}</el-tag> -->
      <!-- <el-card>
          {{ formData.name }}
      </el-card> -->
      <!-- <div class="w-[303px] rounded-full bg-[#DDDFE3] p-1 z-10">
        <div
          class="flex items-center relative after:content-[''] after:block after:bg-white after:h-[30px] after:w-1/2 after:absolute after:top-0 after:left-0 after:transition-transform after:rounded-full"
          :class="
            selectedTab === AiWriteTypeEnum.REPLY && 'after:transform after:translate-x-[100%]'
          "
        >
          <ReuseTab
            v-for="tab in tabs"
            :key="tab.value"
            :text="tab.text"
            :active="tab.value === selectedTab"
            :itemClick="() => switchTab(tab.value)"
          />
        </div>
      </div> -->
    </div>
    <div
      class="px-7 pb-2 flex-grow overflow-y-auto lg:block w-[380px] box-border bg-[#f5f7f9] h-full"
    >
      
      <div>
        <!-- <template v-if="selectedTab === 1">
          <ReuseLabel label="写作内容" hint="示例" :hint-click="() => example('write')" />
          <el-input
            type="textarea"
            :rows="5"
            :maxlength="500"
            v-model="formData.prompt"
            placeholder="请输入写作内容"
            showWordLimit
          />
        </template> -->

        <!-- <template v-else>
          <ReuseLabel label="原文" hint="示例" :hint-click="() => example('reply')" />
          <el-input
            type="textarea"
            :rows="5"
            :maxlength="500"
            v-model="formData.originalContent"
            placeholder="请输入原文"
            showWordLimit
          />

          <ReuseLabel label="回复内容" />
          <el-input
            type="textarea"
            :rows="5"
            :maxlength="500"
            v-model="formData.prompt"
            placeholder="请输入回复内容"
            showWordLimit
          />
        </template> -->
        <el-descriptions>
            <el-descriptions-item >{{ formData.tips }}</el-descriptions-item>
        </el-descriptions>
        <el-input
          v-model="formData.content"
          type="hidden"
        />
        
        <!-- <el-tag :content="formData.name"></el-tag> -->
        <!-- <ReuseLabel label="长度" />
        <Tag v-model="formData.length" :tags="getIntDictOptions(DICT_TYPE.AI_WRITE_LENGTH)" />
        <ReuseLabel label="格式" />
        <Tag v-model="formData.format" :tags="getIntDictOptions(DICT_TYPE.AI_WRITE_FORMAT)" />
        <ReuseLabel label="语气" />
        <Tag v-model="formData.tone" :tags="getIntDictOptions(DICT_TYPE.AI_WRITE_TONE)" />
        <ReuseLabel label="语言" />
        <Tag v-model="formData.language" :tags="getIntDictOptions(DICT_TYPE.AI_WRITE_LANGUAGE)" /> -->
        <el-image :src="formData.image"  fit="contain" class="h-97px w-97px">
          <template #error>
            <div class="h-full w-full flex items-center justify-center">
              <Icon icon="ep:picture"  />
            </div>
          </template>
        </el-image>
        
        <!-- <ul> -->
          <p v-for="compent in compent_json" :key="compent.id">
            <!-- {{ compent.title }} -->
            <ReuseLabel  :label="compent.props.title"/>
            <template v-if="compent.name === 'WidgetTextarea'">
              <!-- <p><el-text>{{ compent.props.title }}</el-text></p> -->
              <el-input
                type="textarea"
                :rows=compent.props.rows
                :maxlength=compent.props.maxlength
                :placeholder="compent.props.placeholder"
                showWordLimit
              />
            </template>
            <template v-if="compent.name === 'WidgetInput'">
              <!-- <p><el-text>{{ compent.props.title }}</el-text></p> -->
              <el-input
                type="text"
                :maxlength=compent.props.maxlength
                :placeholder="compent.props.placeholder"
                showWordLimit
              />
            </template>
            <template v-if="compent.name === 'WidgetRadio'">
              <!-- <p><el-text>{{ compent.props.title }}</el-text></p> -->
              <!-- <el-radio v-model="compent.props.defaultValue" label="1">选项1</el-radio> -->
              <!-- <el-radio-group  v-for="opti in compent.props.options" :key="opti">
                <el-radio-button label={{opti}}>{{ opti }}</el-radio-button>
              </el-radio-group> -->
              <!-- <el-radio v-model="compent.key" label="1">备选项1</el-radio>
              <el-radio v-model="compent.key" label="2">备选项2</el-radio> -->
              <el-radio-group v-model="compent.props.defaultValue">
                <el-radio-button
                v-for="(opti, index) in compent.props.options"
                  :key="index"
                  :label="opti"
                >
                  {{ opti }}
                </el-radio-button>
              </el-radio-group>
              <!-- <el-radio-group v-model="formData.status">
                <el-radio-button
                  v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio-button>
              </el-radio-group> -->
              <!-- <Tag v-model="formData" :tags="getIntDictOptions(DICT_TYPE.AI_WRITE_FORMAT)" /> -->
            </template>
            <template v-if="compent.name === 'WidgetSelect'">
              <!-- <p><el-text>{{ compent.props.title }}</el-text></p> -->
              <el-select v-model="compent.props.defaultValue">
                <el-option  
                  v-for="(opti, index) in compent.props.options"
                  :value="index"
                  :key="index"
                  :label="opti" >{{opti}}</el-option>
              </el-select>
              <!-- <el-select  multiple placeholder="请选择">
                <el-option label="选项一" value="value1"></el-option>
                <el-option label="选项二" value="value2"></el-option>
              </el-select> -->
            </template>
            <template v-if="compent.name === 'WidgetCheckbox'">
              <el-checkbox-group v-model="compent.props.defaultValue">
                <el-checkbox 
                  v-for="(opti, index) in compent.props.options"
                  :key="index"
                  :value="index"
                  :label="opti"
                  >{{opti}}</el-checkbox>
              </el-checkbox-group>
            </template>
          </p>
        <!-- </ul> -->

        <!-- <el-select  v-model="formData.name" placeholder="请选择">
                <el-option label="选项一" value="value1"></el-option>
                <el-option label="选项二" value="value2"></el-option>
        </el-select>
        <el-input
            type="textarea"
            :rows="5"
            :maxlength="500"
            v-model="formData.name"
            placeholder="请输入写作内容"
            showWordLimit
          /> -->
        <!-- <ReuseLabel label="请输入写作内容" />
        <el-input
            type="textarea"
            :rows="5"
            :maxlength="500"
            v-model="formData.name"
            placeholder="请输入写作内容"
            showWordLimit
          />
        <ReuseLabel label="请选择" />
        <el-select >
            <el-option label="start" value="start" />
            <el-option label="end" value="end" />
        </el-select>
        <ReuseLabel label="请输入内容" />
        <el-input
            type="text"
            placeholder="请输入标题"
            showWordLimit
          />
        <ReuseLabel label="请选择类型" />
        <el-radio-group>
              <el-radio-button label="0">任意值</el-radio-button>
              <el-radio-button label="1">范围</el-radio-button>
              <el-radio-button label="2">间隔</el-radio-button>
              <el-radio-button label="3">指定</el-radio-button>
        </el-radio-group>
        <ReuseLabel label="格式" />
        <Tag v-model="formData.format" :tags="getIntDictOptions(DICT_TYPE.AI_WRITE_FORMAT)" /> -->
        

        <!-- <el-select
          multiple
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select> -->
        
        <div class="flex items-center justify-center mt-3">
          <el-button :disabled="isWriting" @click="reset">重置</el-button>
          <el-button :loading="isWriting" @click="submit" color="#846af7">生成</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { createReusableTemplate } from '@vueuse/core'
import { ref } from 'vue'
import Tag from './Tag.vue'
import { WriteVO } from 'src/api/ai/write'
import { omit } from 'lodash-es'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { AiWriteTypeEnum, WriteExample } from '@/views/ai/utils/constants'

import { CreationCategoryApi } from '@/api/ai/creationcategory'
import { CreationModelVO } from 'src/api/ai/creationmodel'

type TabType = WriteVO['type']

const message = useMessage() // 消息弹窗

defineProps<{
  isWriting: boolean
}>()

const emits = defineEmits<{
  (e: 'submit', params: Partial<CreationModelVO>)
  (e: 'example', param: 'write' | 'reply')
  (e: 'reset')
}>()

/** 点击示例的时候，将定义好的文章作为示例展示出来 **/
const example = (type: 'write' | 'reply') => {
  formData.value = {
    ...initData,
    ...omit(WriteExample[type], ['data'])
  }
  emits('example', type)
}

/** 重置，将表单值作为初选值 **/
const reset = () => {
  formData.value = { ...initData }
  emits('reset')
}

const selectedTab = ref<TabType>(AiWriteTypeEnum.WRITING)
const tabs: {
  text: string
  value: TabType
}[] = [
  { text: '撰写', value: AiWriteTypeEnum.WRITING },
  { text: '回复', value: AiWriteTypeEnum.REPLY }
]
const [DefineTab, ReuseTab] = createReusableTemplate<{
  active?: boolean
  text: string
  itemClick: () => void
}>()

/**
 * 可以在 template 里边定义可复用的组件，DefineLabel，ReuseLabel 是采用的解构赋值，都是 Vue 组件
 *
 * 直接通过组件的形式使用，<DefineLabel v-slot="{ label, hint, hintClick }"> 中间是需要复用的组件代码 <DefineLabel />，通过 <ReuseLabel /> 来使用定义的组件
 * DefineLabel 里边的 v-slot="{ label, hint, hintClick }"相当于是解构了组件的 prop，需要注意的是 boolean 类型，需要显式的赋值比如 <ReuseLabel :flag="true" />
 * 事件也得以 prop 形式传入，不能是 @event的形式，比如下面的 hintClick 需要<ReuseLabel :hintClick="() => { doSomething }"/>
 *
 * @see https://vueuse.org/createReusableTemplate
 */
const [DefineLabel, ReuseLabel] = createReusableTemplate<{
  label: string
  class?: string
  hint?: string
  hintClick?: () => void
}>()

const initData: CreationModelVO = {
  id: 0,
  name: '',
  image: '',
  sort: 0,
  categoryId: 0,
  status: 1,
  content: '',
  tips: '',
  contextNum: 10,
  topP: 1,
  presencePenalty: 1,
  frequencyPenalty: 1,
  n: 5,
  maxTokens: 2048,
  temperature: 1,
  form: ''
}
const formData = ref<CreationModelVO>({ ...initData })

/** 用来记录切换之前所填写的数据，切换的时候给赋值回来 **/
// const recordFormData = {} as Record<AiWriteTypeEnum, CreationModelVO>

/** 切换tab **/
// const switchTab = (value: TabType) => {
//   if (value !== selectedTab.value) {
//     // 保存之前的久数据
//     recordFormData[selectedTab.value] = formData.value
//     selectedTab.value = value
//     // 将之前的旧数据赋值回来
//     formData.value = { ...initData, ...recordFormData[value] }
//   }
// }

/** 提交写作 */
const submit = () => {
  // if (selectedTab.value === 2 && !formData.value.originalContent) {
  //   message.warning('请输入原文')
  //   return
  // }
  // if (!formData.value.prompt) {
  //   message.warning(`请输入${selectedTab.value === 1 ? '写作' : '回复'}内容`)
  //   return
  // }
  // emits('submit', {
  //   /** 撰写的时候没有 originalContent 字段**/
  //   ...(selectedTab.value === 1 ? omit(formData.value, ['originalContent']) : formData.value),
  //   /** 使用选中 tab 值覆盖当前的 type 类型 **/
  //   type: selectedTab.value
  // })
}
let compent_json = []
/** 查询列表 */
const getList = async (id:number) => {
  // loading.value = true
  try {
    const data = await CreationCategoryApi.getCreationModel(id);
    // console.log(data);
    formData.value=data
    const compent_str = formData.value.form
    console.log(compent_str);
    compent_json = JSON.parse(compent_str);
    
  } catch (error) {
    console.error("Parsing error:", error);
  }
}
/** 初始化 **/
onMounted(() => {
  const route = useRoute();
    // 获取路由参数
  const id = route.query.id;

  const myid = parseInt(id, 10);
  if (isNaN(myid)) {
    // 处理 NaN 的情况，例如设置默认值或抛出错误
    console.error('转换失败，查询参数 id 不是一个有效的数字');
    return;
  }
  getList(myid);
  
})

</script>
